package com.FengChaoSystem.servlet;

import com.FengChaoSystem.pojo.Occupy;
import com.FengChaoSystem.pojo.Order;
import com.FengChaoSystem.pojo.PageNeed;
import com.FengChaoSystem.pojo.User;
import com.FengChaoSystem.service.OccupyImpl;
import com.FengChaoSystem.service.OccupyService.OccupyService;
import com.FengChaoSystem.service.OrderImpl;
import com.FengChaoSystem.service.OrderService.OrderService;
import com.FengChaoSystem.service.UserImpl;
import com.FengChaoSystem.service.UserService.UserService;
import com.FengChaoSystem.tool.ThreadPool;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;

@WebServlet("/Order/*")
public class OrderServlet extends BaseServlet{
    private OrderImpl service=new OrderService();

    /**
     * 获取客户的所有订单消息
     * @param request
     * @param response
     * @throws Exception
     */
    public void selectAllOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String currentPage = request.getParameter("CurrentPage");
        String pageSize = request.getParameter("PageSize");

        HttpSession session = request.getSession();
        String phone = (String)session.getAttribute("phone");
        PageNeed pageNeed=new PageNeed();

        pageNeed.setPhone(phone);
        pageNeed.setBegin((Integer.parseInt(currentPage)-1)*Integer.parseInt(pageSize));
        pageNeed.setSize(Integer.parseInt(pageSize));
        List<Order> orders = service.selectAllOrderByCondition(pageNeed);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Order order:orders) {
            if(order.getStatus()==3)
            {String startTime = dateFormat.format(order.getStartTime());
            String endTime=dateFormat.format(order.getEndTime());
            order.setStartTime(null);
            order.setEndTime(null);
            JSONObject orderObject = (JSONObject) JSON.toJSON(order);
            orderObject.put("startTime", startTime);
            orderObject.put("endTime", endTime);

            // 将整合后的 JSONObject 转换为字符串输出
            String jsonString = orderObject.toJSONString();
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);
            System.out.println(jsonString);}
            else {
                String startTime = dateFormat.format(order.getStartTime());
                order.setStartTime(null);
                order.setEndTime(null);
                JSONObject orderObject = (JSONObject) JSON.toJSON(order);
                orderObject.put("startTime", startTime);

                // 将整合后的 JSONObject 转换为字符串输出
                String jsonString = orderObject.toJSONString();
                response.setContentType("text/json;charset=utf-8");
                response.getWriter().write(jsonString);
                System.out.println(jsonString);
            }
        }
    }

    /**
     * 获取所有待取订单的信息
     * @param request
     * @param response
     * @throws Exception
     */
    public void selectAllUnGetOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String currentPage = request.getParameter("CurrentPage");
        String pageSize = request.getParameter("PageSize");
        HttpSession session = request.getSession();
        String phone = (String)session.getAttribute("phone");
        System.out.println(phone);
        PageNeed pageNeed=new PageNeed();
        pageNeed.setPhone(phone);
        pageNeed.setSize(Integer.parseInt(pageSize));
        pageNeed.setBegin((Integer.parseInt(currentPage)-1)*Integer.parseInt(pageSize));
        List<Order> orders = service.selectAllUnGetOrderByCondition(pageNeed);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Order order:orders) {
            String startTime = dateFormat.format(order.getStartTime());
            order.setStartTime(null);
            order.setEndTime(null);
            JSONObject orderObject = (JSONObject) JSON.toJSON(order);
            orderObject.put("startTime", startTime);

            // 将整合后的 JSONObject 转换为字符串输出
            String jsonString = orderObject.toJSONString();
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);
            System.out.println(jsonString);
        }
    }

    /**
     * 以下两个都是获取总共有几条数据
     * @param request
     * @param response
     * @throws Exception
     */
    public void getTotalCountOfAllOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        String phone = (String)session.getAttribute("phone");
        User user=new User();
        user.setPhone(phone);
        List<Order> orders = service.selectAllOrder(user);
        int totalCount = orders.size();
        String jsonString = JSON.toJSONString(totalCount);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);

    }


    public void getTotalCountOfAllUnGetOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        String phone = (String)session.getAttribute("phone");
        User user=new User();
        user.setPhone(phone);
        List<Order> orders = service.selectAllUnGetOrder(user);
        int totalCount = orders.size();
        String jsonString = JSON.toJSONString(totalCount);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

    /**
     * 根据订单号来获取订单的消息
     * @param request
     * @param response
     * @throws Exception
     */


    public void selectOrdersByOnlyId(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        int userId = (int) session.getAttribute("userId");

        String onlyId = request.getParameter("onlyId");

        Order order=new Order();
        order.setOnlyId(onlyId);
        order.setToUserId(userId);
        Order result = service.selectOrdersByOnlyId(order);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 将 bar 对象转换为 JSONObject

        // 格式化创建时间并添加到 JSONObject 中
        String endTime=null;
        if(result!=null&&result.getEndTime()!=null){
         endTime = dateFormat.format(result.getEndTime());}

        if (result!=null) {
            String startTime = dateFormat.format(result.getStartTime());
            result.setEndTime(null);
            result.setStartTime(null);
            JSONObject orderObject = (JSONObject) JSON.toJSON(result);
            orderObject.put("endTime", endTime);
            orderObject.put("startTime",startTime);

            // 将整合后的 JSONObject 转换为字符串输出
            String jsonString = orderObject.toJSONString();

            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);
        }
    }

    /**
     * 以下两个就是获取自己寄出的货物信息
     * @param request
     * @param response
     * @throws Exception
     */
    public void selectAllUnSendOrderByCondition(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String currentPage = request.getParameter("CurrentPage");
        String pageSize = request.getParameter("PageSize");

        HttpSession session = request.getSession();
        int id= (int)session.getAttribute("userId");
        PageNeed pageNeed=new PageNeed();

        pageNeed.setUserId(id);
        pageNeed.setBegin((Integer.parseInt(currentPage)-1)*Integer.parseInt(pageSize));
        pageNeed.setSize(Integer.parseInt(pageSize));
        List<Order> orders = service.selectAllUnSendOrderByCondition(pageNeed);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Order order:orders) {
            String startTime = dateFormat.format(order.getStartTime());
            order.setStartTime(null);
            order.setEndTime(null);
            JSONObject orderObject = (JSONObject) JSON.toJSON(order);
            orderObject.put("startTime", startTime);

            // 将整合后的 JSONObject 转换为字符串输出
            String jsonString = orderObject.toJSONString();
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);
        }
    }

    public void selectAllSendingOrderByCondition(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String currentPage = request.getParameter("CurrentPage");
        String pageSize = request.getParameter("PageSize");
        HttpSession session = request.getSession();
        int id = (int)session.getAttribute("userId");

        PageNeed pageNeed=new PageNeed();
        pageNeed.setUserId(id);
        pageNeed.setSize(Integer.parseInt(pageSize));
        pageNeed.setBegin((Integer.parseInt(currentPage)-1)*Integer.parseInt(pageSize));
        List<Order> orders = service.selectAllSendingOrderByCondition(pageNeed);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Order order:orders) {
            String startTime = dateFormat.format(order.getStartTime());
            order.setStartTime(null);
            order.setEndTime(null);
            JSONObject orderObject = (JSONObject) JSON.toJSON(order);
            orderObject.put("startTime", startTime);

            // 将整合后的 JSONObject 转换为字符串输出
            String jsonString = orderObject.toJSONString();
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);

        }
    }

    /**
     * 以下两个就是获取对应的数据条数
     * @param request
     * @param response
     * @throws Exception
     */
    public void getCountOfSendingOrders(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        int id = (int)session.getAttribute("userId");
        User user=new User();
        user.setId(id);
        List<Order> orders = service.selectAllSendingOrder(user);
        int totalCount = orders.size();
        String jsonString = JSON.toJSONString(totalCount);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }
    public void getCountOfUnSendingOrders(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        int id = (int)session.getAttribute("userId");
        User user=new User();
        user.setId(id);
        List<Order> orders = service.selectAllUnSendOrder(user);
        int totalCount = orders.size();
        String jsonString = JSON.toJSONString(totalCount);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

    /**
     * 拿货物的时候要用，会判断是否超时，并进行收费或取消定时任务
     * @param request
     * @param response
     * @throws Exception
     */
    public void getGood(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        int userId = (int)session.getAttribute("userId");
        BufferedReader reader = request.getReader();
        String param = reader.readLine();
        Occupy occupy= JSON.parseObject(param, Occupy.class);
        Occupy hasOrder = service.hasOrder(occupy);
        if(hasOrder==null){
            System.out.println("can not find");
            response.getWriter().write("can not find");
            return;
        }
        Order temp=new Order();
        temp.setOnlyId(hasOrder.getOnlyId());

        Order result = service.select(temp);

        if(result==null){
            response.getWriter().write("can not find");
            return;
        } else if (result.getFromUserId()==userId) {

            response.getWriter().write("???");
            return;
        } else if(result.getStatus()==3 ){

            response.getWriter().write("The order has accept");
            return;
        }



        Timestamp putTime = result.getPutTime();
        Timestamp nowTime  =new Timestamp(System.currentTimeMillis());

        long putTimeLong = putTime.getTime();
        long nowTimeLong = nowTime.getTime();
        int requireMoney=0;
        if(nowTimeLong-putTimeLong>120*1000){


            requireMoney+=10;
            int times= (int) ((nowTimeLong-putTimeLong)/(1000*90));
            System.out.println(times);
            if(times>=6){
                requireMoney=40;
            }else{
                requireMoney+=5*times;
            }
        }

        int toUserId=result.getToUserId();
        UserImpl UserService=new UserService();
        User user=new User();
        user.setId(toUserId);
        User selectUserInfo = UserService.selectUserInfo(user);
        int nowMoney = selectUserInfo.getNowMoney();
        if(nowMoney<requireMoney){
            response.getWriter().write("you are pool");
            return;
        }
        else {
            user.setNowMoney(nowMoney-requireMoney);
            UserService.updateNowMoney(user);
        }


        result.setStatus(3);
        service.updateStatus(result);
        OccupyImpl temp2=new OccupyService();
        temp2.updateOccupyStatus(occupy);
        service.updateGetTime(result);

        ThreadPool.removeTask(hasOrder.getOnlyId());

        String jsonString = JSON.toJSONString(requireMoney);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);


    }
    }
